package l2s.gameserver.scripts.custom;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import l2s.commons.configuration.Config;
import l2s.commons.db.DatabaseFactory;
import l2s.gameserver.ThreadPoolManager;
import l2s.gameserver.model.actor.instance.L2PcInstance;

/**
 * User: Shaitan Date: 14.02.11 Time: 7:32
 */
public class MMOTopDeamon
{
	private static final Logger _log = LoggerFactory.getLogger("MMOTopDeamon");
	
	public static MMOTopDeamon getInstance()
	{
		return SingletonHolder._instance;
	}
	
	protected MMOTopDeamon()
	{
		if (Config.MMOTopEnable)
		{
			_log.info("Service: Loading MmoTop Parser...");
			ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new startParce(), 60000, Config.MMOTopRefreshTime * 60 * 1000);
		}
		else
		{
			_log.info("Service: MmoTop Parser - Disabled.");
		}
	}
	
	protected class startParce implements Runnable
	{
		@Override
		public void run()
		{
			try
			{
				getPage(Config.MMOTopUrl);
				parse();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	BufferedReader reader;
	
	protected void parse()
	{
		String line;
		
		try
		{
			while ((line = reader.readLine()) != null)
			{
				StringTokenizer st = new StringTokenizer(line, "\t. :");
				while (st.hasMoreTokens())
				{
					try
					{
						st.nextToken();
						int day = Integer.parseInt(st.nextToken());
						int month = Integer.parseInt(st.nextToken());
						int year = Integer.parseInt(st.nextToken());
						int hour = Integer.parseInt(st.nextToken());
						int minute = Integer.parseInt(st.nextToken());
						int second = Integer.parseInt(st.nextToken());
						st.nextToken();
						st.nextToken();
						st.nextToken();
						st.nextToken();
						String name = st.nextToken();
						L2PcInstance player = VoteUtils.loadPlayer(name);
						if ((player != null) && player.isOnline())
						{
							Calendar calendar = Calendar.getInstance();
							calendar.set(Calendar.YEAR, year);
							calendar.set(Calendar.MONTH, month);
							calendar.set(Calendar.DAY_OF_MONTH, day);
							calendar.set(Calendar.HOUR_OF_DAY, hour);
							calendar.set(Calendar.MINUTE, minute);
							calendar.set(Calendar.SECOND, second);
							calendar.set(Calendar.MILLISECOND, 0);
							long time = calendar.getTimeInMillis() / 1000;
							checkAndSave(name, time);
						}
					}
					catch (Exception e)
					{
					}
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private static void checkAndSave(String name, long time)
	{
		_log.info("MMOTopDeamon: Checking mmotop.ru....");
		int nVotes = 0;
		try (Connection con = DatabaseFactory.getConnection())
		{
			PreparedStatement fps = con.prepareStatement("SELECT * FROM `mmotop_votes` WHERE `name`=? AND `time`=? LIMIT 1");
			fps.setString(1, name);
			fps.setLong(2, time);
			ResultSet rs = fps.executeQuery();
			if (!rs.next())
			{
				L2PcInstance player = VoteUtils.loadPlayer(name);
				if (player != null)
				{
					player.addItem("mmotop", Config.MMOTopRewardItemId, Config.MMOTopRewardItemCount, null, true);
					if (player.isOnline())
					{
						player.sendMessage("Вам начислена награда за голосование в рейтинге MMOTop.");
					}
					player.store();
					fps = con.prepareStatement("INSERT INTO `mmotop_votes` (`name`, `time`) VALUES (?, ?)");
					fps.setString(1, name);
					fps.setLong(2, time);
					fps.execute();
					nVotes++;
				}
			}
			_log.info("MMOTopDeamon: " + nVotes + " vote(s) parsed");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	protected void getPage(String address)
	{
		try
		{
			URL url = new URL(address);
			new BufferedReader(new InputStreamReader(url.openStream(), "Cp1251"));
		}
		catch (Exception e)
		{
		}
	}
	
	private static class SingletonHolder
	{
		protected static final MMOTopDeamon _instance = new MMOTopDeamon();
	}
	
	public static void onLoad()
	{
		MMOTopDeamon.getInstance();
	}
}
